package com.hongdee.scm.inputinvoice.service.impl;

import com.hongdee.common.dao.IHibernateDao;
import com.hongdee.common.util.TokenUtil;
import com.hongdee.scm.carInvoicePrice.dao.ITScmCarInvoicePriceDao;
import com.hongdee.scm.carInvoicePrice.entity.TScmCarInvoicePrice;
import com.hongdee.scm.common.service.ICommonService;
import com.hongdee.scm.inputinvoice.dao.ITScmInvoiceDao;
import com.hongdee.scm.inputinvoice.entity.TScmCostDifference;
import com.hongdee.scm.inputinvoice.entity.TScmInputInvoice;
import com.hongdee.scm.inputinvoice.entity.TScmInvoiceDetail;
import com.hongdee.scm.inputinvoice.entity.TScmInvoiceHistory;
import com.hongdee.scm.inputinvoice.service.ITScmInvoiceService;
import com.hongdee.scm.invioce.service.ITCrmCarInvoiceService;
import com.hongdee.scm.monthlybalance.service.ITScmMonthlyBalanceService;
import com.hongdee.scm.util.SerialNumFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by Mr. Xu on 2017/5/12.
 */
@Service
public class TScmInvoiceServiceImpl implements ITScmInvoiceService {
    private String tabName = "T_Scm_Input_Invoice";
    private String tabNameDetail = "T_Scm_Input_Invoice_detail";
    @Autowired
    private ICommonService common;
    @Autowired
    private ITScmInvoiceDao itScmInvoiceDao;
    @Autowired
    private IHibernateDao iHibernateDao;
    @Autowired
    private ITScmCarInvoicePriceDao invoicePriceDao;
    @Autowired
    private ICommonService iCommonService;
    @Autowired
    private ITScmMonthlyBalanceService itScmMonthlyBalanceService;
    @Autowired
    private ITCrmCarInvoiceService itCrmCarInvoiceService;
    //车型对照表
    private String tabCarModel = " t_bc_carmodel";
    //配置对照表
    private String tabCarConfig = "t_bc_carconfigure";

    /**
     * 发票分页
     *
     * @param uid
     * @param start
     * @param limit
     * @param data
     * @return
     * @throws Exception
     */
    @Override
    public Map page(String uid, String start, String limit, Map data) throws Exception {
        List params = new ArrayList();
        StringBuffer sql = new StringBuffer();
        Boolean hasWhere = false;
        String oid = TokenUtil.getCompanyId(uid);
        sql.append("select p.*,DATE_FORMAT(invoice_date,'%Y-%m-%d') invoice_date1 from " + tabName+" p ");
        if (!oid.equals("")) {
            hasWhere = common.appendWhereIfNeed(sql, hasWhere);
            sql.append(" p.company_id =  ? ");
            params.add(oid);
        }
        //发票日期起
        if (data.get("invoiceStratDate") != null && data.get("invoiceStratDate") != "") {
            hasWhere = common.appendWhereIfNeed(sql, hasWhere);
            sql.append(" DATE_FORMAT(invoice_date,'%Y-%m-%d') >=  ? ");
            params.add(data.get("invoiceStratDate"));
        }
        //发票日期止
        if (data.get("invoiceStopDate") != null && data.get("invoiceStopDate") != "") {
            hasWhere = common.appendWhereIfNeed(sql, hasWhere);
            sql.append(" DATE_FORMAT(invoice_date,'%Y-%m-%d') <=  ? ");
            params.add(data.get("invoiceStopDate"));
        }
        //发票号
        if (data.get("inputName") != null && data.get("inputName") != "") {
            hasWhere = common.appendWhereIfNeed(sql, hasWhere);
            sql.append(" p.invoice_num like  ? ");
            params.add("%" + data.get("inputName") + "%");
        }
        //vin查询
        if(data.get("vin") != null && data.get("vin") != ""){
            hasWhere = common.appendWhereIfNeed(sql, hasWhere);
            sql.append(" p.id in (select invoice_id from t_scm_input_invoice_detail where vin like ? ) ");
            params.add("%" + data.get("vin") + "%");
        }
        sql.append(" order by DATE_FORMAT(invoice_date, '%Y-%m-%d') DESC ");
        return this.itScmInvoiceDao.page(sql.toString(), params.toArray(), start, limit);
    }

    /**
     * 发票明细
     *
     * @param id
     * @return
     * @throws Exception
     */
    @Override
    public Map pageDetail(String id, String start, String limit,String vin) throws Exception {
        List params = new ArrayList();
        StringBuffer sql = new StringBuffer();
        sql.append("select tid.id as invoiceDetailId,tid.*,tsc.*,tsc.car_model model_name, tsc.configure configure_name, tt.warehouse_id from " + tabNameDetail + " tid ")
                .append(" left join t_scm_car tsc on tid.car_id=tsc.id ")
                .append(" left join t_scm_stock tt on tid.car_id=tt.car_id ")
                .append(" where tid.invoice_id = ? ");
        params.add(id);

        //vin查询
        if(vin!=null&&!vin.equals("")){
            sql.append(" and tid.vin like ?");
            params.add("%"+vin+"%");
        }
        return this.itScmInvoiceDao.page(sql.toString(), params.toArray(), start, limit);
    }

    /**
     * 发票明细
     *
     * @param id
     * @return
     * @throws Exception
     */
//    @Override
//    public List listDetail(String id) throws Exception {
//        List params = new ArrayList();
//        StringBuffer sql = new StringBuffer();
//        sql.append("select tid.id as invoiceDetailId,tid.*,tsc.*,tbm.model_name,tcc.configure_name from " + tabNameDetail + " tid")
//                .append(" left join t_scm_car tsc on tid.vin=tsc.vin ")
//                .append(" left join " + tabCarModel + " tbm on tsc.car_model_id=tbm.id")
//                .append(" left join " + tabCarConfig + " tcc on tsc.configure_id=tcc.id")
//                .append(" where invoice_id = ? ");
//        params.add(id);
//        return this.itScmInvoiceDao.list(sql.toString(), params.toArray());
//    }

    /**
     * 发票保存
     *
     * @param data
     * @param uid
     * @throws Exception
     */
    @Override
    public void saveorupdate(TScmInputInvoice data, String type, String uid) throws Exception {

        if(data.getId()==null){//新增
            //判断发票编号是否重复
            if (data.getInvoiceNum() != null && !data.getInvoiceNum().equals("")) {
                if (this.itScmInvoiceDao.info("select * from t_scm_input_invoice where invoice_num =?", data.getInvoiceNum()).size() > 0) {
                    throw new Exception("发票编号不可重复");
                }
            }
            Map map = TokenUtil.getUser(uid);
            if (map.get("uName") != null && !map.get("uName").equals("")) {
                data.setInputName(map.get("uName").toString());
            }
            //如果是红票，回写对应普票的红票金额；
            if (data.getInvoiceType().equals("2") || data.getInvoiceType().equals("3")) {
                if (!data.getRelationId().equals("")) {
                    this.itScmInvoiceDao.executeSQL("update " + tabName + " set invoice_red_money=invoice_red_money+? where id = ?", data.getInvoiceTotal(), data.getRelationId());
                    //若为整冲红票，更新关联普通发票的车辆为红冲发票
                    if (type.equals("1")) {
                        this.itScmInvoiceDao.executeSQL("update t_scm_car set finance_type ='4' where id in (select car_id from " +
                                " t_scm_input_invoice_detail where invoice_id = ?  )", data.getRelationId());
                    }
                } else {
                    throw new Exception("未关联增值税发票！");
                }
            } else {
                //如果不是红票，默认红票金额为0
                data.setInvoiceRedMoney("0");
                //默认总金额为0
                data.setInvoiceTempTotal("0");
            }
            //默认未月结
            data.setMonthlyStatus("0");
            if (data.getId() == null) {
                if (!data.getInvoiceTotal().matches("^[0-9]+(.[0-9]{0,2})?$")) {
                    throw new Exception("请输正确发票金额！");
                }
                data.setCreateUser(uid);
                data.setCreateTime(Calendar.getInstance().getTimeInMillis());
                data.setCompanyId(TokenUtil.getCompanyId(uid));
                data.setInvoiceDate(new SimpleDateFormat("yyyy-MM-dd").format(new Date()));
                this.itScmInvoiceDao.saveOrUpdate(data);
                //刷新流水号
                common.updateSerialNumber(common.serialNumber("0"));
            } else {
                throw new Exception("不能修改！");
            }
        }else{//修改
            this.changeInvoice(data,uid);
        }
    }

    /**
     * 发票修改
     * @param data
     * @param uid
     * @throws Exception
     */
    private void changeInvoice(TScmInputInvoice data,String uid) throws Exception{

        TScmInputInvoice ti = (TScmInputInvoice) this.iHibernateDao.findEntity(TScmInputInvoice .class,data.getId());
        data.setId(ti.getId());
        data.setCreateTime(ti.getCreateTime());
        data.setCreateUser(ti.getCreateUser());
        data.setUpdateTime(System.currentTimeMillis());
        data.setUpdateUser(uid);
        this.itScmInvoiceDao.saveOrUpdate(data);
    }

    /**
     * 发票明细保存
     *
     * @param data
     * @param uid
     * @throws Exception
     */
    @Override
    public void saveorupdateDetail(List<Map> data, String uid, String id) throws Exception {
        if (data.size() > 0) {
            for (Map map : data) {
                TScmInvoiceDetail entity = new TScmInvoiceDetail();
                if (map.get("vin") == null || map.get("vin").equals("")) {

                }
                entity.setVin(map.get("vin").toString());
                entity.setCreateUser(uid);
                entity.setInvoiceId(id);
                entity.setCarId(map.get("id").toString());
                entity.setCreateTime(Calendar.getInstance().getTimeInMillis());
                if (map.get("purchasePrice") != null && !map.get("purchasePrice").equals("")) {
                    entity.setEstimate(map.get("purchasePrice").toString());
                }
                if (map.get("carModel") != null && !map.get("carModel").equals("")) {
                    entity.setCarModel(map.get("carModel").toString());
                }
                if (map.get("certificateNum") != null && !map.get("certificateNum").equals("")) {
                    entity.setCertificateNum(map.get("certificateNum").toString());
                }
                if (map.get("carPrice") != null && !map.get("carPrice").equals("")) {
                    entity.setCarPrice(map.get("carPrice").toString());
                }

                this.itScmInvoiceDao.saveOrUpdate(entity);
            }
        } else {
            throw new Exception("请选择车辆！");
        }
        updateTotal(id);

    }

    /**
     * 发票明细保存
     *
     * @param data
     * @param uid
     * @throws Exception
     */
    @Override
    public Map saveorupdateInvoiceDetail(List<TScmInvoiceDetail> data, String uid, String id) throws Exception {
        if (data.size() > 0) {
            for (TScmInvoiceDetail entity : data) {
                //判断车辆是否已存在发票中
                if (this.itScmInvoiceDao.list("select * from " + tabNameDetail + " where car_id = ? ", entity.getCarId()).size() > 0) {
                    throw new Exception("vin为" + entity.getVin() + "的车辆已存在发票中！");
                }
                if (StringUtils.isEmpty(entity.getId()))  ////实际为车辆ID，下面做转换
                {
                    continue;
                }
                entity.setCarId(entity.getId());
                entity.setId(null);
                //绑定发票id
                entity.setInvoiceId(id);
                //判断发票金额输入情况
                if (entity.getCarPrice() != null && !entity.getCarPrice().equals("")) {
                    if (entity.getCarPrice().matches("^[0-9]+(.[0-9]{0,2})?$")) {
                        this.itScmInvoiceDao.saveOrUpdate(entity);
                    } else {
                        throw new Exception("请输入金额数字！");
                    }
                } else {
                    //发票金额未填并暂估金额为空
                    throw new Exception("请输入金额数字！");
//                    entity.setCarPrice("0");
//                    this.itScmInvoiceDao.saveOrUpdate(entity);
                }
                //根据vin判断车辆是否销售若销售生成成本差异，若未销售冲估
                //已销售生成成本差异价格
                Map isSale = this.itScmInvoiceDao.info("select * from t_scm_car where id = ? ", entity.getCarId());
                //if (isSale.get("saleFlag").equals("1")) {
                    Date dt = new Date();
                    //最后的aa表示“上午”或“下午”    HH表示24小时制    如果换成hh表示12小时制
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd HH:mm:ss");
                    //this.itScmInvoiceDao.executeSQL("update T_Scm_Car_Price_Detail set cost_difference = ?-?,cost_difference_date=? where vin = ? ",
                    //        entity.getCarPrice(), entity.getEstimate(), sdf.format(dt),entity.getVin());
                    TScmCostDifference tScmCostDifference = new TScmCostDifference();
                    tScmCostDifference.setCreateUser(uid);
                    tScmCostDifference.setCreateTime(Calendar.getInstance().getTimeInMillis());
                    tScmCostDifference.setVin(entity.getVin());
                    tScmCostDifference.setModifyDate(sdf.format(dt));
                    tScmCostDifference.setOldCost(String.valueOf(isSale.get("estimatePrice")));
                    tScmCostDifference.setNewCost(entity.getCarPrice());
                    if(!tScmCostDifference.getOldCost().equals(tScmCostDifference.getNewCost())) {
                        this.itScmInvoiceDao.saveOrUpdate(tScmCostDifference);
                    }
                //}
                //更新车辆价格明细表
                StringBuffer updatSql = new StringBuffer();
                //vin转车辆ID
                Map mapTemp = this.itScmInvoiceDao.info("select * from t_scm_car where id = ? ", entity.getCarId());
               //zhc 20170725 updatSql.append(" update T_Scm_Car_Price_Detail set cost = ? ,purchase_invoice_price = ?  where car_id = ? ");
               //zhc 20170725 this.itScmInvoiceDao.executeSQL(updatSql.toString(), entity.getCarPrice(),entity.getCarPrice(), mapTemp.get("id"));
                //回写车辆已录入发票,将invoice_status置为1
               //zhc 20170725 this.itScmInvoiceDao.executeSQL("update t_scm_car set finance_type='3' where id = ? ",   entity.getCarId());
                //如果保存车辆为红冲车辆，则将其改为正常车辆
                if (mapTemp.get("isRed") != null && !StringUtils.isEmpty(mapTemp.get("isRed"))) {
                    if (mapTemp.get("isRed").toString().equals("1")) {
                        this.itScmInvoiceDao.executeSQL("update t_scm_car set finance_type = '2' where id = ? ", entity.getCarId());
                    }
                }
                this.itScmInvoiceDao.executeSQL("update t_scm_car set finance_type = '3' where id = ?",entity.getCarId());
                //销售单匹配车辆
                itCrmCarInvoiceService.refreshCar(uid,entity.getCarId());

            }
        } else {
            throw new Exception("请选择车辆！");
        }
        //更新总金额
        updateTotal(id);
        return this.getCarCount(id);
    }

    /**
     * 修改车辆价格
     *
     * @param vins
     * @param price
     * @throws Exception
     */
    @Override
    public Map updatePrice(String[] vins, String iid, String price, String uid) throws Exception {
        //查看发票是否月结，月结发票无法修改单车发票金额
        String dates = this.itScmInvoiceDao.info("select date_format(invoice_date,'%Y-%m-%d') invoice_date from t_scm_input_invoice where id = ? ", iid).get("invoiceDate").toString();
        String cid= TokenUtil.getCompanyId(uid);
        /*String stopDate = this.itScmInvoiceDao.info("select * from t_scm_monthlybalance where monthly_balance_month = ?",d.toString()).get("monthlyBalanceStopDate").toString();
        //获取当前时间
        String currentT = iCommonService.currentTime();
        //已月结并且修改金额的日期要比月结日期大
        if(stopDate.equals("")||stopDate==null){
            throw new Exception("请进行月结!");
        }else{
            if(status.equals("0") && Integer.parseInt(currentT)>Integer.parseInt(stopDate)&&currentT.substring(0,5).compareTo(d.toString())>0){
                //this.changePrice(vins,iid,price,uid);
            }
        }*/

        if (this.itScmMonthlyBalanceService.ifMonthlyBalance(cid,new SimpleDateFormat("yyyy-MM-dd").parse(dates))) {
            throw new Exception("月结发票无法修改！");
        }
        //修改发票明细发票金额
        if (vins.length > 0) {
                //修改发票明细发票金额
                StringBuffer hql = new StringBuffer();
                hql.append("update T_Scm_Input_Invoice_detail  set car_price =  " + price)
                        .append(" where vin = ? ");
                for (String vin : vins) {
                    //查询车辆历史发票价格
                    Map temp = new HashMap();
                    if (vin != null) {
                        temp = this.itScmInvoiceDao.info("select * from T_Scm_Input_Invoice_detail where vin = ? ", vin);
                    }
                    List params = new ArrayList();
                    params.add(vin);
                    this.itScmInvoiceDao.executeSQL(hql.toString(), params.toArray());
                    //已销售生成成本差异价格
                    Map isSale = this.itScmInvoiceDao.info("select * from t_scm_car where id = ? ", temp.get("carId"));
                    if (isSale.get("status").equals("2")) {
                        Date dt = new Date();
                        //最后的aa表示“上午”或“下午”    HH表示24小时制    如果换成hh表示12小时制
                        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd HH:mm:ss");
                        TScmCostDifference tScmCostDifference = new TScmCostDifference();
                        tScmCostDifference.setCreateUser(uid);
                        tScmCostDifference.setCreateTime(Calendar.getInstance().getTimeInMillis());
                        tScmCostDifference.setVin(String.valueOf(vin));
                        tScmCostDifference.setCarId(String.valueOf(temp.get("carId")));
                        tScmCostDifference.setModifyDate(sdf.format(dt));
                        tScmCostDifference.setOldCost(String.valueOf(temp.get("carPrice")));
                        tScmCostDifference.setNewCost(price);
                        if(!tScmCostDifference.getOldCost().equals(tScmCostDifference.getNewCost())) {
                            this.itScmInvoiceDao.saveOrUpdate(tScmCostDifference);
                        }
                    }
                    //插入历史修改车辆发票价格实体
                    TScmInvoiceHistory historyEntity = new TScmInvoiceHistory();
                    historyEntity.setCreateUser(uid);
                    historyEntity.setCreateTime(Calendar.getInstance().getTimeInMillis());
                    //修改发票金额时间
                    Date currentTime = new Date();
                    SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd HH:mm:ss");
                    historyEntity.setModifyDate(formatter.format(currentTime));
                    historyEntity.setNewPrice(price);
                    historyEntity.setHistoryPrice(String.valueOf(temp.get("carPrice")));
                    historyEntity.setVin(String.valueOf(vin));
                    this.itScmInvoiceDao.saveOrUpdate(historyEntity);

                    //t_scm_invoice_price中冲掉修改价格前的正入单,新增一个新的正入单
                    if(this.itScmInvoiceDao.info("select * from t_scm_invoice_price where car_id =? and invoices_type = '3'",temp.get("carId")).size()>0){
                        this.itScmInvoiceDao.executeSQL("update t_scm_invoice_price set invoices_type='-3' where car_id =? and invoices_type = '3'",temp.get("carId"));
                    }
                    TScmCarInvoicePrice tcip = new TScmCarInvoicePrice();
                    tcip.setCreateUser(uid);
                    tcip.setCreateTime(Calendar.getInstance().getTimeInMillis());
                    tcip.setInvoicesPrice(price);
                    tcip.setInvoicesType("3");
                    tcip.setCarId(temp.get("carId").toString());
                    tcip.setConncetionNo(SerialNumFactory.generateSerialNum(uid, "3"));
                    tcip.setStrat_printTime(Calendar.getInstance().getTime());
                    tcip.setPrintCount("1");
                    this.invoicePriceDao.saveOrUpdate(tcip);
                    this.itScmInvoiceDao.executeSQL("update t_scm_car set invoice_price = ? where id =?",price,temp.get("carId"));
                }
            }
            //修改发票总金额
            updateTotal(iid);
            //修改车辆价格明细表
          /*zhc 20170725  StringBuffer carhql = new StringBuffer();
            carhql.append("update T_Scm_Car_Price_Detail  set purchase_invoice_price = ?,cost = ?  ");
            List params1 = new ArrayList();
            params1.add(price);
            params1.add(price);
            if (ids.length > 0) {
                carhql.append(" where vin in ( ");
                for (Object vin : ids) {
                    carhql.append(" ? , ");
                    params1.add(vin);
                }
                carhql.append(" '' ) ");
            }
            this.itScmInvoiceDao.executeSQL(carhql.toString(), params1.toArray());  */
        return this.getCarCount(iid);

    }


    /**
     * 删除车辆明细
     *
     * @param ids
     * @throws Exception
     */
    @Override
    public Map  delInvoiceDetail (String[] ids,String iid,String uid) throws Exception {

        String cid = TokenUtil.getCompanyId(uid);
        String dates="";
        Map map =this.itScmInvoiceDao.info("select date_format(invoice_date,'%Y-%m-%d') invoice_date from t_scm_input_invoice where id = ?",iid);
        if(map.get("invoiceDate")!=null&&!"".equals(map.get("invoiceDate"))){
            dates = map.get("invoiceDate").toString();
            if(itScmMonthlyBalanceService.ifMonthlyBalance(cid,new SimpleDateFormat("yyyy-MM-dd").parse(dates))){
                throw new Exception("月结后不能移除车辆");
            }
        }else{

        }
        if (ids.length > 0) {
            for (Object id : ids) {

                if(this.itScmInvoiceDao.list("select * from t_scm_sale_order_detail o where status = '0' and exists " +
                        "(select d.car_id from t_scm_input_invoice_detail d where o.car_id = d.car_id and id =?)",id).size()>0){
                    throw new Exception("已销售的车辆不能移除");
                }else{
                    String hql = "delete from TScmInvoiceDetail where id = :id";
                    Map params = new HashMap();
                    params.put("id", id);

                /*zhc 20170720*/
                    //回写车辆未录入发票,将车辆财务状态改成暂估状态
                    if(this.itScmInvoiceDao.info("select * from t_scm_invoice_price o where car_id = (select d.car_id from t_scm_input_invoice_detail d where o.car_id = d.car_id and id =? ) and invoices_type='1'",id).size()>0){
                        this.itScmInvoiceDao.executeSQL("update t_scm_car set finance_type='2' where id in (select " +
                                " car_id from T_Scm_Input_Invoice_detail where id = ? )  ",id);
                    }else{//直接正式入库的车辆(先来发票后来车)
                        this.itScmInvoiceDao.executeSQL("update t_scm_car set finance_type='1' where id in (select " +
                                " car_id from T_Scm_Input_Invoice_detail where id = ? )  ",id);
                    }
                    //冲估单和正入单的状态改为-2和-3
                    String carId = this.itScmInvoiceDao.info("select * from t_scm_input_invoice_detail where id =?",id).get("carId").toString();
                    if(this.itScmInvoiceDao.info("select * from t_scm_invoice_price where car_id =? and invoices_type = '2' ",carId).size()>0){
                        this.itScmInvoiceDao.executeSQL("update t_scm_invoice_price set invoices_type ='-2' where car_id = ? and invoices_type = '2'",carId);
                    }
                    if(this.itScmInvoiceDao.info("select * from t_scm_invoice_price where car_id =? and invoices_type = '3' ",carId).size()>0){
                        this.itScmInvoiceDao.executeSQL("update t_scm_invoice_price set invoices_type ='-3' where car_id = ? and invoices_type = '3'",carId);
                    }

                    //T_Scm_Car_Price_Detail发票金额移除
             /*zhc 20170725  this.itScmInvoiceDao.executeSQL("update T_Scm_Car_Price_Detail set cost =estimate_price" +
                        " where vin in (select vin from T_Scm_Input_Invoice_detail where id = ? ) ",id);  */

                    this.iHibernateDao.executeHqlWithParams(hql, params);
                }

            }
        }
        updateTotal(iid);
        return this.getCarCount(iid);
    }

    private void updateTotal(String iid) throws Exception {
        //更新发票总金额
        StringBuffer updateTotal = new StringBuffer();
        StringBuffer selectTotal = new StringBuffer();
        selectTotal.append("select round(sum(ifnull(car_price,0)),2) as total from t_scm_input_invoice_detail where invoice_id = ? ");
        updateTotal.append("update T_Scm_Input_Invoice set invoice_temp_total=? where id=? ");
        List paramsMap = new ArrayList();
        Map temp = this.itScmInvoiceDao.info(selectTotal.toString(), iid);
        paramsMap.add(temp.get("total"));
        paramsMap.add(iid);
        this.itScmInvoiceDao.executeSQL(updateTotal.toString(), paramsMap.toArray());
    }

    /**
     * 红冲发票删除车辆
     *
     * @param ids
     * @param uid
     * @throws Exception
     */
    @Override
    public void deleteCar(String[] ids, String uid) throws Exception {
        StringBuffer del = new StringBuffer();
        del.append("delete from t_scm_car where id in ( ");
        List params = new ArrayList();
        if (ids.length > 0) {
            for (String id : ids) {
                del.append(" ?, ");
                params.add(id);
            }
            del.append(" '') ");
            this.itScmInvoiceDao.executeSQL(del.toString(), params.toArray());
        } else {
            throw new Exception("请选择红冲车辆！");
        }
    }


    /**
     * 查询历史发票价格调整明细
     *
     * @param data
     * @param start
     * @param limit
     * @param uid
     * @return
     * @throws Exception
     */
    @Override
    public Map historyPage(Map data, String start, String limit, String uid) throws Exception {

        StringBuffer sql = new StringBuffer();
        List params = new ArrayList();
        sql.append("select p.*,tsc.warehouse,tsc.company_id,tsc.car_model from T_SCM_INVOICE_HISTORY p ")
                .append(" left join t_scm_car tsc on p.vin = tsc.vin ");
        if (data.get("vin") != null && !StringUtils.isEmpty(data.get("vin"))) {
            sql.append(" where vin like  ? ");
            params.add("%" + data.get("vin") + "%");
        }
        return this.itScmInvoiceDao.page(sql.toString(), params.toArray(), start, limit);
    }

    //查询发票流水号
    @Override
    public String invoiceSerialNumber() throws Exception {
        return "FP" + common.currentTime() + common.serialNumber("0");
    }


    /**
     * 是否存在整冲红票
     *
     * @param invoiceNum
     * @return
     * @throws Exception
     */
    @Override
    public boolean existRedInvoice(String invoiceNum) throws Exception {
        if (!invoiceNum.equals("")) {
            return (this.itScmInvoiceDao.info("select * from " + tabName + " where relation_num = ? and invoice_type='3'" +
                    " limit 1 ", invoiceNum).size() > 0);
        } else {
            return false;}
    }

    /**
     *
     * @param vin
     * @return
     * @throws Exception
     */
    @Override
    public Map historyInvoicePrice(String vin) throws Exception {
        Map map = new HashMap();
        if (!StringUtils.isEmpty(vin)) {
            Map temp = this.itScmInvoiceDao.info("select * from t_scm_invoice_history where vin = ?  order by modify" +
                    "_date desc limit 1 ", vin);
            if(temp.size()>0){
                if(temp.get("historyPrice")!=null&&!StringUtils.isEmpty(temp.get("historyPrice"))){
                    map.put("historyPrice",temp.get("historyPrice"));
                    map.put("newPrice",temp.get("newPrice"));
                    map.put("success",true);
                }else{
                    throw new Exception("不存在历史价格！");
                }
            }else {
                throw new Exception("不存在历史价格！");
            }
        }else {
            map.put("success",false);
        }
        return map;
    }

    /**
     * 发票登记总金额
     * @param id
     * @return
     * @throws Exception
     */
    @Override
    public Map getCarCount(String id) throws Exception{
        return this.itScmInvoiceDao.info("select invoice_temp_total as invoice_total from t_scm_input_invoice where id = ?",id);
    }

    /**
     * 发票查询详情
     * @param id
     * @param uid
     * @return
     * @throws Exception
     */
    @Override
    public Map infoInvoice(String id,String uid) throws Exception{

        Map map = this.itScmInvoiceDao.info("select * from t_scm_input_invoice where id = ?",id);
        return map;
    }
}
